package com.woldier.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woldier.common.R;
import com.woldier.entity.Dish;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Paths;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    /*用于指定保存在那个文件夹下*/
    @Value("${reggie.dir}")
    private   String BASE_DIR;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("upload")
    public R upload(MultipartFile file, HttpSession session)  {

        /*前期处理判断basedir是否存在 不存在则创建*/
        File file1 = new File(BASE_DIR);
        if(!file1.exists()){
            file1.mkdir();
        }


        /*得到后缀*/
        String originalFilename = file.getOriginalFilename();
        String perfix = originalFilename.substring(originalFilename.lastIndexOf('.'));
        /*进行文件名拼接*/
        /*基础地址+当前时间+用户id+文件名后缀 */
        String append_dir =  System.currentTimeMillis() +"_"+ (Long) session.getAttribute("employee") + perfix;
        String fileName = BASE_DIR +append_dir;
        /*当前file是一个临时文件 如果不保存 此次请求结束就会删除*/
        try {
            file.transferTo(new File(fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(append_dir);
    }

    @GetMapping("download")
    public void download(String name ,HttpServletResponse response){

        try {
            /*根据传入的文件名获取输入流*/
            FileInputStream inputStream = new FileInputStream(new File(BASE_DIR+name));

            /*response获取输出流*/
            ServletOutputStream outputStream = response.getOutputStream();

            /*把输入流读出时的容器*/
            byte[] bytes = new byte[1024];
            /*接受读出的byte个数*/
            int len = 0;

            /*当len!=-1时继续读*/
            while((len = inputStream.read(bytes))!=-1){
                /*写入 从0开始到len*/
                outputStream.write(bytes,0,len);
                /*刷新*/
                outputStream.flush();
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

    }



}
